//
//  DBDevices.m
//  CareRingApp
//
//  Created by Linktop on 2022/6/7.
//

#import "DBDevices.h"
#import "DBValueSuper.h"
#import "DBSleepData.h"
#import "DBHistoryDataSr03.h"
#import "OTAHeader.h"

NSString * const TABLE_NM_DEVICE = @"table_devices";

NSString * const DEV_OTHERINFO_KEY_SIZE = @"dev_size";
NSString * const DEV_OTHERINFO_KEY_COLOR = @"dev_color";
NSString * const DEV_OTHERINFO_KEY_FIRMWARE_VERSION = @"dev_firm_version";
NSString * const DEV_OTHERINFO_KEY_SN = @"dev_sn";
NSString * const DEV_OTHERINFO_CHIP = @"dev_chip";
NSString * const DEV_OTHERINFO_GENERATION = @"dev_generation";
NSString * const DEV_OTHERINFO_SUPP_SPORT_MODE = @"supp_sportMode"; //是否支持运动模式
NSString * const DEV_OTHERINFO_CHARGEW_MODE = @"charge_mode"; //充电类型
NSString * const DEV_OTHERINFO_SUPP_ECG = @"supp_ecg"; //是否支持ecg
NSString * const DEV_OTHERINFO_SUPP_PROJECT_ID = @"supp_prj_id"; //设备型号

@implementation DBDevices

-(instancetype)init
{
    if (self = [super init]) {
        self.otherInfo = [[DeviceOtherInfo alloc]init];
    }
    return self;
}
//创建数据库
+(void)createTable
{
    
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        //创建数据库表
        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@( macAddress TEXT primary key, otherInfo TEXT)", TABLE_NM_DEVICE];
        bool succ = [db executeUpdate:sql];
        NSLog(@"create table %@ result =%d ", TABLE_NM_DEVICE, succ);
        
    }];
    
}

-(void)insert:(void(^)(BOOL succ))complete
{
    
    DB_WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        DB_STRONG_SELF
        [db beginTransaction];
        
        NSString *sqlString = [NSString stringWithFormat:  @"INSERT OR IGNORE INTO %@ ( macAddress,  otherInfo) VALUES (?,?)", TABLE_NM_DEVICE];
        BOOL succ = [db executeUpdate:sqlString,
                     strongSelf.macAddress,
                     [strongSelf.otherInfo jsonString]
                    ];
        
        [db commit];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete) {
                complete(succ);
            }
        });
        
    }];
}

-(void)updateOtherInfo:(void(^)(BOOL succ))complete
{
    
    DB_WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        DB_STRONG_SELF
//        [db beginTransaction];
        
        NSString *sqlString = [NSString stringWithFormat:  @"UPDATE %@ set otherInfo = ? WHERE macAddress = ?", TABLE_NM_DEVICE];
        BOOL succ = [db executeUpdate:sqlString,
                        [self.otherInfo jsonString],
                     self.macAddress
                    ];
        
//        [db commit];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete) {
                complete(succ);
            }
        });
        
    }];
}

-(void)deleteFromTable:(void (^)(void))cmpBlk
{
    DB_WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        DB_STRONG_SELF
        [db beginTransaction];
        
        NSString *sql =  [NSString stringWithFormat:@"DELETE FROM %@ WHERE macAddress = ? ", TABLE_NM_DEVICE];
        [db executeUpdate:sql, strongSelf.macAddress];
        
        [DBSleepData clearColumnBy:strongSelf.macAddress DB:db];
        
        [DBHistoryDataSr03 clearColumnBy:strongSelf.macAddress DB:db];
        
        [db commit];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (cmpBlk) {
                cmpBlk();
            }
        });
       
    }];
}

+(void)queryAllByCpmplete:(void(^)(NSMutableArray<DBDevices *> *results))cmpBlk
{
    
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {

        NSMutableArray<DBDevices *> *results = [NSMutableArray new];
        NSString *sql =  [NSString stringWithFormat:@"SELECT rowid, * FROM %@ ", TABLE_NM_DEVICE];
        FMResultSet *rs ;
       
        rs = [db executeQuery:sql];
        
        while ([rs next]) {
            DBDevices *device = [[DBDevices alloc]init];
            device.cId = @([rs intForColumn:@"rowid"]);
            device.macAddress = [rs stringForColumn:@"macAddress"];
            
            DeviceOtherInfo *info = [[DeviceOtherInfo alloc]init];
            NSString *infoString = [rs stringForColumn:@"otherInfo"];
            [info parseJasonString:infoString];
            device.otherInfo = info;
            
            [results addObject:device];
        }
        [rs close];
       
        if (cmpBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cmpBlk(results);
            });
        }
       
    }];
}

-(void)chooseOTAugument:(void(^)(NSString * _Nullable cat))blk
{
    NSString *cat = nil;
    
    if (self.otherInfo.projectId == PROJ_NOT_SUPPORT) { // 旧的设备逻辑
        if (self.otherInfo.mainChipType == MAIN_CHIP_14531_00) {
            cat = SR03_CAT;
        }
        if (self.otherInfo.chargeType == 1) { // 无线
            cat = SR09_CAT;
        }
        
        if (self.otherInfo.chargeType == 2) {// nfc
            cat = SR09_N_CAT;
        }
        
        // 转换为base64+urlenc编码
        NSString *encodeCat = [self transCatToBs64UrlEncode:cat];
        
        if (blk) {
            blk(encodeCat);
        }
        return ;
    }
    
    if (self.otherInfo.projectId == PROJ_SR26) {
            // sr26
        cat = SR26_CAT;
    }
    
    if (self.otherInfo.projectId == PROJ_SR23_NFC) {
        cat = SR23_CAT;
    }
    
    if (self.otherInfo.projectId == PROJ_SR03) {
        cat = SR03_CAT;
    }
    
    if (self.otherInfo.projectId == PROJ_SRO9W) {
        cat = SR09_CAT;
    }
    if (self.otherInfo.projectId == PROJ_SRO9N) {
        cat = SR09_N_CAT;
    }
    
    if (self.otherInfo.projectId == PROJ_SR01A) { // 日本戒指
        cat = SR01A_CAT;
    }
    
    // 转换为base64+urlenc编码
    NSString *encodeCat = [self transCatToBs64UrlEncode:cat];
    
    if (blk) {
        blk(encodeCat);
    }
    
    return;
}

-(NSString *)transCatToBs64UrlEncode:(NSString *)cat {
    
    if (!cat.length) {
        return nil;
    }
    
//    NSDictionary *dict = @{
//        @"sr09_t" : @"c3IwOV90",
//        @"nexring03_t" : @"bmV4cmluZzAzX3Q%3D",
//        @"sr26_t" : @"c3IyNl90",
//        @"sr09n_t" : @"c3IwOW5fdA%3D%3D",
//        @"sr23_t" : @"c3IyM190",
//        
//        @"nexring03" : @"bmV4cmluZzAz",
//        @"sr26" : @"c3IyNg%3D%3D",
//        @"sr23" : @"c3IyMw%3D%3D",
//        @"sr09" : @"c3IwOQ%3D%3D",
//        @"sr09n" : @"c3IwOW4%3D",
//    
//    };
    
    NSString *base64Encode =  [self base64UrlEncode:cat];
    
    return base64Encode;//dict[cat];
    
    
}


-(NSString *)base64UrlEncode:(NSString *)inputString {
    if (!inputString) {
        return nil;
    }
//    NSString *inputString = @"Your input string";
    NSData *data = [inputString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64EncodedString = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    // urlencode
    
    NSCharacterSet *allowedCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"!*'();:@&=+$,/?%#[]"] invertedSet];

    NSString *encodedUrlString = [base64EncodedString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];

    return  encodedUrlString;
}

@end


/// 其他信息
@implementation DeviceOtherInfo

- (instancetype)init
{
    self = [super init];
    if (self) {
//        [self makeDefaultValue];
    }
    return self;
}
// 序列化为json
-(NSString *)jsonString
{
    NSString *jsonString;
    
    NSDictionary *dict = @{DEV_OTHERINFO_KEY_SIZE :@(self.size),
                           DEV_OTHERINFO_KEY_COLOR : @(self.color),
                           DEV_OTHERINFO_KEY_SN : self.sn ? self.sn : @"",
                           DEV_OTHERINFO_KEY_FIRMWARE_VERSION  : self.fireWareVersion ?  self.fireWareVersion : @"",
                           DEV_OTHERINFO_CHIP: @(self.mainChipType),
                           DEV_OTHERINFO_GENERATION : @(self.deviceGeneration),
                           DEV_OTHERINFO_SUPP_SPORT_MODE : @(self.isSupportSportMode),
                           DEV_OTHERINFO_CHARGEW_MODE : @(self.chargeType),
                           DEV_OTHERINFO_SUPP_ECG :@(self.isSupportEcg),
                           DEV_OTHERINFO_SUPP_PROJECT_ID : @(self.projectId),

    };
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    if (error) {
        DebugNSLog(@"%s error=%@", __FUNCTION__, error);
    }
    return jsonString;
}
// 反解析json
-(NSDictionary *)parseJasonString:(NSString *)jsonString
{
   
    if (!jsonString) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&err];
    if (err) {
        DebugNSLog(@"%s error=%@", __FUNCTION__, err);
        
    } else {
        self.color = [dict[DEV_OTHERINFO_KEY_COLOR] unsignedIntegerValue];
        self.size = [dict[DEV_OTHERINFO_KEY_SIZE] integerValue];
        self.sn = dict[DEV_OTHERINFO_KEY_SN];
        self.fireWareVersion = dict[DEV_OTHERINFO_KEY_FIRMWARE_VERSION];
        self.mainChipType = [dict[DEV_OTHERINFO_CHIP] unsignedIntegerValue];
        self.deviceGeneration = [dict[DEV_OTHERINFO_GENERATION] unsignedIntegerValue];
        self.isSupportSportMode = [dict[DEV_OTHERINFO_SUPP_SPORT_MODE] boolValue];
        self.isSupportEcg = [dict[DEV_OTHERINFO_SUPP_ECG] boolValue];
        self.projectId = [dict[DEV_OTHERINFO_SUPP_PROJECT_ID] unsignedIntValue];

        if (dict[DEV_OTHERINFO_CHARGEW_MODE]) {
            self.chargeType = [dict[DEV_OTHERINFO_CHARGEW_MODE] intValue];
        } else {
            self.chargeType = CHARGE_UNKNOW;
        }


    }
    
    return dict;
}


/// 转换为 a.b.c格式
-(NSString *)transFirmVersionToRemoteType
{
    NSArray<NSString *> *arr = [self.fireWareVersion componentsSeparatedByString:@"."];
    
    NSMutableString *res = [NSMutableString new];
    for (int i = 0; i < arr.count; i++) {
        NSString *temp = arr[i];
        [res appendFormat:@"%d", temp.intValue];
        if (i != arr.count- 1) {
            [res appendString:@"."];
        }
    }
    return res;
}




@end
